from flask import Blueprint, request, jsonify
from flask_jwt_extended import jwt_required
from app import db
from app.models import Permission
from app.utils.decorators import admin_required

permissions_bp = Blueprint('permissions', __name__)

@permissions_bp.route('/', methods=['GET'])
@jwt_required()
@admin_required
def get_permissions():
    """获取权限列表"""
    page = request.args.get('page', 1, type=int)
    per_page = request.args.get('per_page', 100, type=int)
    search = request.args.get('search', '')
    type_filter = request.args.get('type', '')
    
    query = Permission.query
    
    if search:
        query = query.filter(
            db.or_(
                Permission.name.contains(search),
                Permission.code.contains(search),
                Permission.path.contains(search)
            )
        )
    
    if type_filter:
        query = query.filter(Permission.type == type_filter)
    
    pagination = query.paginate(
        page=page, per_page=per_page, error_out=False
    )
    
    permissions = pagination.items
    
    return jsonify({
        'permissions': [perm.to_dict() for perm in permissions],
        'pagination': {
            'page': page,
            'per_page': per_page,
            'total': pagination.total,
            'pages': pagination.pages
        }
    }), 200

@permissions_bp.route('/<int:permission_id>', methods=['GET'])
@jwt_required()
@admin_required
def get_permission(permission_id):
    """获取权限详情"""
    permission = Permission.query.get(permission_id)
    
    if not permission:
        return jsonify({'message': '权限不存在'}), 404
    
    return jsonify({'permission': permission.to_dict()}), 200

@permissions_bp.route('/', methods=['POST'])
@jwt_required()
@admin_required
def create_permission():
    """创建权限"""
    data = request.get_json()
    
    if not data:
        return jsonify({'message': '请求数据不能为空'}), 400
    
    name = data.get('name')
    code = data.get('code')
    type = data.get('type')
    path = data.get('path', '')
    method = data.get('method', '')
    description = data.get('description', '')
    
    if not name or not code or not type:
        return jsonify({'message': '权限名称、编码和类型不能为空'}), 400
    
    # 检查权限编码是否已存在
    if Permission.query.filter_by(code=code).first():
        return jsonify({'message': '权限编码已存在'}), 400
    
    permission = Permission(
        name=name,
        code=code,
        type=type,
        path=path,
        method=method,
        description=description
    )
    
    try:
        db.session.add(permission)
        db.session.commit()
        return jsonify({
            'message': '权限创建成功',
            'permission': permission.to_dict()
        }), 201
    except Exception as e:
        db.session.rollback()
        return jsonify({'message': '权限创建失败'}), 500

@permissions_bp.route('/<int:permission_id>', methods=['PUT'])
@jwt_required()
@admin_required
def update_permission(permission_id):
    """更新权限"""
    permission = Permission.query.get(permission_id)
    
    if not permission:
        return jsonify({'message': '权限不存在'}), 404
    
    data = request.get_json()
    
    if not data:
        return jsonify({'message': '请求数据不能为空'}), 400
    
    # 允许更新的字段
    allowed_fields = ['name', 'code', 'type', 'path', 'method', 'description', 'is_active']
    
    for field in allowed_fields:
        if field in data:
            setattr(permission, field, data[field])
    
    try:
        db.session.commit()
        return jsonify({
            'message': '权限更新成功',
            'permission': permission.to_dict()
        }), 200
    except Exception as e:
        db.session.rollback()
        return jsonify({'message': '权限更新失败'}), 500

@permissions_bp.route('/<int:permission_id>', methods=['DELETE'])
@jwt_required()
@admin_required
def delete_permission(permission_id):
    """删除权限"""
    permission = Permission.query.get(permission_id)
    
    if not permission:
        return jsonify({'message': '权限不存在'}), 404
    
    try:
        db.session.delete(permission)
        db.session.commit()
        return jsonify({'message': '权限删除成功'}), 200
    except Exception as e:
        db.session.rollback()
        return jsonify({'message': '权限删除失败'}), 500 